package com.meals.system.api.seller;

import com.meals.system.api.admin.param.BatchIdParam;
import com.meals.system.api.seller.param.GoodsAddParam;
import com.meals.system.api.seller.param.GoodsUpdateParam;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.config.annotation.TokenToSeller;
import com.meals.system.entity.SystemSeller;
import com.meals.system.entity.SystemSellerToken;
import com.meals.system.entity.WhitesMealGoods;
import com.meals.system.service.WhitesMealSystemGoodsService;
import com.meals.system.util.BeanUtil;
import com.meals.system.util.PageQueryUtil;
import com.meals.system.util.Result;
import com.meals.system.util.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/10
 */
@RestController
@Api(value = "v1", tags = "2-3.白餐商家管理商品相关接口")
@RequestMapping("/seller-api/v1")
public class WhitesMealSellerGoodInfoAPI {

    private static final Logger logger = LoggerFactory.getLogger(WhitesMealSellerGoodInfoAPI.class);

    @Resource
    private WhitesMealSystemGoodsService whitesMealSystemGoodsService;

    /**
     * 列表
     */
    @RequestMapping(value = "/goods/list", method = RequestMethod.GET)
    @ApiOperation(value = "商家的商品列表", notes = "可以根据名称和商家爱状态筛选")
    public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
                       @RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
                       @RequestParam(required = false) @ApiParam(value = "商品名称") String goodsName,
                       @RequestParam(required = false) @ApiParam(value = "上架状态 0-上架 1-下架") Integer goodsSellStatus,
                       @TokenToSeller SystemSeller loginSeller){
        logger.info("seller:{}", loginSeller.toString());
        if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
            return ResultGenerator.genFailResult("分页参数异常！");
        }
        Map params = new HashMap(8);
        params.put("page", pageNumber);
        params.put("limit", pageSize);
        if (!StringUtils.isEmpty(goodsName)) {
            params.put("goodsName", goodsName);
        }
        if (goodsSellStatus != null) {
            params.put("goodsSellStatus", goodsSellStatus);
        }
        // 将sellerId 传到param参数中，包装给pageUtil
        params.put("sellerId", loginSeller.getSellerId());
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(whitesMealSystemGoodsService.getWhitsMealGoodsPage(pageUtil));
    }


    /**
     * 添加商品
     */
    @RequestMapping(value = "/goods", method = RequestMethod.POST)
    @ApiOperation(value = "新增商品信息", notes = "新增商品信息")
    public Result save(@RequestBody @Valid GoodsAddParam goodsAddParam, @TokenToSeller SystemSellerToken loginSeller){
        logger.info("seller:{}", loginSeller.toString());
        WhitesMealGoods whitesMealGoods = new WhitesMealGoods();

        // 获取商家id并赋予给goodsAddParam
        // 不提供sellerId这个属性给商家，直接在这里设置好sellerId
        goodsAddParam.setSellerId(loginSeller.getSellerId());

        BeanUtil.copyProperties(goodsAddParam, whitesMealGoods);
        String result = whitesMealSystemGoodsService.saveWhitesMealGoods(whitesMealGoods);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)){
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    @RequestMapping(value = "/good", method = RequestMethod.PUT)
    @ApiOperation(value = "修改商品信息", notes = "修改商品信息")
    public Result update(@RequestBody @Valid GoodsUpdateParam goodsUpdateParam, @TokenToSeller SystemSellerToken loginSeller){
        logger.info("seller:{}", loginSeller.toString());
        WhitesMealGoods whitesMealGoods = new WhitesMealGoods();

        // 不提供sellerId这个属性给商家，直接在这里设置好sellerId
        goodsUpdateParam.setSellerId(loginSeller.getSellerId());

        BeanUtil.copyProperties(goodsUpdateParam,whitesMealGoods);
        String result = whitesMealSystemGoodsService.updateWhitesMealGoods(whitesMealGoods);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)){
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }

    }

    /**
     * 详情
     */
    @GetMapping("/goods/{id}")
    @ApiOperation(value = "获取单条商品信息", notes = "根据id查询")
    public Result info(@PathVariable("id") Long id, @TokenToSeller SystemSellerToken loginSeller){
        logger.info("seller:{}", loginSeller.toString());
        Map goodsInfo = new HashMap(8);
        WhitesMealGoods goods = whitesMealSystemGoodsService.getWhitesMealGoodsById(id);
        if (goods == null){
            return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        goodsInfo.put("goods", goods);
        return ResultGenerator.genSuccessResult(goodsInfo);
    }


    /**
     * 批量修改销售状态
     */
    @RequestMapping(value = "goods/status/{selleStatus}", method = RequestMethod.PUT)
    @ApiOperation(value = "批量修改销售状态", notes = "批量修改销售状态")
    public Result delete(@RequestBody BatchIdParam batchIdParam, @PathVariable("sellerStatus") int sellStatus, @TokenToSeller SystemSellerToken loginSeller){
        logger.info("seller:{}", loginSeller.toString());
        if (batchIdParam == null || batchIdParam.getIds().length < 1){
            return ResultGenerator.genFailResult("参数异常!");
        }
        if (sellStatus != Constants.SELL_STATUS_UP && sellStatus != Constants.SELL_STATUS_DOWN){
            return ResultGenerator.genFailResult("状态异常");
        }
        if (whitesMealSystemGoodsService.batchUpdateSellStatus(batchIdParam.getIds(),sellStatus)){
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败!");
        }
    }
}
